<template>
  <div class="login-container">
    <div class="login-card">
      <h2>登录</h2>

      <form @submit.prevent="handleLogin">
        <div class="form-group">
          <label for="username">用户名</label>
          <input
            type="text"
            id="username"
            v-model="username"
            required
            :disabled="authStore.loading"
          >
        </div>

        <div class="form-group">
          <label for="password">密码</label>
          <input
            type="password"
            id="password"
            v-model="password"
            required
            :disabled="authStore.loading"
          >
        </div>

        <button
          type="submit"
          class="login-btn"
          :disabled="authStore.loading"
        >
          <span v-if="authStore.loading">登录中...</span>
          <span v-else>登录</span>
        </button>
      </form>

      <div v-if="authStore.error" class="error-message">
        {{ authStore.error }}
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useUserStore } from '@/stores/user.js'
import { useRouter } from 'vue-router'

// 初始化状态
const authStore = useUserStore()
const router = useRouter()
const username = ref('')
const password = ref('')

// 登录处理
const handleLogin = async () => {
  const success = await authStore.login(username.value, password.value)
  if (success) {
    // 登录成功跳转到/home页面
    router.push('/home')
  }
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f5f5f5;
}

.login-card {
  width: 350px;
  padding: 2rem;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

h2 {
  text-align: center;
  margin-bottom: 1.5rem;
  color: #333;
}

.form-group {
  margin-bottom: 1rem;
}

label {
  display: block;
  margin-bottom: 0.5rem;
  color: #666;
}

input {
  width: 100%;
  padding: 0.8rem;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 1rem;
}

.login-btn {
  width: 100%;
  padding: 0.8rem;
  background-color: #42b983;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 1rem;
  cursor: pointer;
  transition: background-color 0.3s;
}

.login-btn:hover {
  background-color: #359e75;
}

.login-btn:disabled {
  background-color: #9ae6b4;
  cursor: not-allowed;
}

.error-message {
  margin-top: 1rem;
  color: #e53e3e;
  text-align: center;
  padding: 0.5rem;
  background-color: #fef2f2;
  border-radius: 4px;
}
</style>